import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';

class ImageCropPage extends StatefulWidget {
  const ImageCropPage({super.key});

  @override
  State<ImageCropPage> createState() => _ImageCropPageState();
}

class _ImageCropPageState extends State<ImageCropPage> {
  final ImagePicker _picker = ImagePicker();

  Future<void> _selectAndCropImage() async {
    final XFile? picked = await _picker.pickImage(source: ImageSource.gallery);
    if (picked == null) {
      // 用户取消选择图片，主动关闭页面并返回 null
      Navigator.of(context).pop(null);
      return;
    }

    final CroppedFile? cropped = await ImageCropper().cropImage(
      sourcePath: picked.path,
      aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
      uiSettings: [
        AndroidUiSettings(
          toolbarTitle: '裁剪头像',
          toolbarColor: Colors.blue,
          toolbarWidgetColor: Colors.white,
          initAspectRatio: CropAspectRatioPreset.square,
          lockAspectRatio: true,
        ),
        IOSUiSettings(
          title: '裁剪头像',
        )
      ],
    );

    if (cropped != null) {
      Navigator.of(context).pop(File(cropped.path));
    } else {
      Navigator.of(context).pop(null); // 用户取消裁剪，返回 null
    }
  }

  @override
  void initState() {
    super.initState();
    // 页面加载立即触发
    Future.microtask(() => _selectAndCropImage());
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      backgroundColor: Colors.black,
      body: Center(child: CircularProgressIndicator()),
    );
  }
}
